package net.lainiao.reptile;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;

/**
 * Created by Administrator on 2017/1/11.
 */
public class UrlHelper {
    private static RedisHelper redisHelper;
    public static String getUrl(String url,String current){
        if(StringUtils.isBlank(url)){
            return null;
        }
        if(url.startsWith("#")){
            return null;
        }
        if(url.startsWith("javascript")){
            return null;
        }
        String resUrl=null;
        if(url.startsWith("http")){
            resUrl=url;
        }
        else if(url.startsWith("//")){
            if(current.startsWith("https")){
                resUrl="https:"+url;
            }
            else{
                resUrl="http:"+url;
            }
        }
        else if(url.startsWith("/")){
            String baseUrl=UrlHelper.getHostUrl(current);
            resUrl=baseUrl+url;
        }

        else if(url.startsWith("?")){
            String baseUrl=UrlHelper.getBaseUrl(current,false);
            resUrl=baseUrl+url;
        }

        else if(url.startsWith(".")){
            String baseUrl=UrlHelper.getPointUrl(current);
            resUrl=baseUrl+url;
        }
        else{
            String baseUrl=UrlHelper.getBaseUrl(current,true);
            resUrl=baseUrl+url;
        }
        return resUrl.trim();
    }

    //获取基于Point定位L
    private static String getPointUrl(String url){
        String[] urls=url.split("[?]");
        String res=urls[0];
        int lastIndex=res.lastIndexOf("/");
        if(url.startsWith("https")&&lastIndex==7){
            if(url.endsWith("/")){
                return url;
            }else{
                return url+"/";
            }
        }
        if(url.startsWith("http")&&lastIndex==6){
            if(url.endsWith("/")){
                return url;
            }else{
                return url+"/";
            }
        }
        return res.substring(0,lastIndex);
    }

    //获取基准的URL
    private static String getBaseUrl(String url,boolean append){
        String[] urls=url.split("[?]");
        String res=urls[0];
        if(append&&(!res.endsWith("/"))){
            return res+"/";
        }
        if((!append)&&res.endsWith("/")){
            return res.substring(0,res.length()-2);
        }
        return res;
    }

    //获取基于Host的URL
    private static String getHostUrl(String url){
        String[] tems=url.split("/");
        String scheme=tems[0];
        String host=tems[2];
        return scheme+"//"+host;
    }

    public static void addProcess(String url){
        if(UrlHelper.redisHelper==null){
            ApplicationContext context=ApplicationCommon.applicationContext;
            UrlHelper.redisHelper=context.getBean(RedisHelper.class);
        }
        UrlHelper.redisHelper.addProcessed(url);
    }

}
